"""
Resource Manager

简化的资源管理器，负责根据computeUnit计算Pod的资源限制和请求。
"""

from typing import Dict, Any
import math
import logging


class ResourceManager:
    """简化的资源管理器"""

    def __init__(self):
        """初始化资源管理器"""
        self.logger = logging.getLogger(__name__)

    def calculate_pod_resources(self, compute_unit: int, replicas: int) -> Dict[str, Any]:
        """
        根据computeUnit和副本数计算单个Pod的资源限制和请求
        
        Args:
            compute_unit: 计算单元数量
            replicas: 副本数量
            
        Returns:
            包含CPU和内存限制和请求的字典
        """
        if compute_unit <= 0:
            raise ValueError("computeUnit must be greater than 0")
        
        if replicas <= 0:
            raise ValueError("replicas must be greater than 0")
        
        # 1个计算单元 = limit CPU 1000m, limit RAM 1Gi, request = limit/2
        total_cpu_limit = compute_unit * 1000  # millicores
        total_memory_limit = compute_unit * 1  # Gi
        
        # 计算单个Pod的资源（向下取整）
        cpu_limit_per_pod = math.floor(total_cpu_limit / replicas)
        memory_limit_per_pod = math.floor(total_memory_limit / replicas)
        
        # 计算请求资源（limit/2，向下取整）
        cpu_request_per_pod = math.floor(cpu_limit_per_pod / 2)
        memory_request_per_pod = math.floor(memory_limit_per_pod / 2)
        
        # 确保最小资源值
        cpu_limit_per_pod = max(cpu_limit_per_pod, 10)  # 最少10m CPU
        memory_limit_per_pod = max(memory_limit_per_pod, 32)  # 最少32Mi内存
        cpu_request_per_pod = max(cpu_request_per_pod, 5)  # 最少5m CPU请求
        memory_request_per_pod = max(memory_request_per_pod, 16)  # 最少16Mi内存请求
        
        return {
            "requests": {
                "cpu": f"{cpu_request_per_pod}m",
                "memory": f"{memory_request_per_pod}Mi"
            },
            "limits": {
                "cpu": f"{cpu_limit_per_pod}m",
                "memory": f"{memory_limit_per_pod}Mi"
            }
        }

    def get_resource_summary(self, compute_unit: int, replicas: int) -> Dict[str, Any]:
        """
        获取资源分配摘要
        
        Args:
            compute_unit: 计算单元数量
            replicas: 副本数量
            
        Returns:
            资源分配摘要
        """
        pod_resources = self.calculate_pod_resources(compute_unit, replicas)
        
        # 计算总资源
        total_cpu_limit = compute_unit * 1000
        total_memory_limit = compute_unit * 1
        
        return {
            "compute_unit": compute_unit,
            "replicas": replicas,
            "total_resources": {
                "cpu_limit": f"{total_cpu_limit}m",
                "memory_limit": f"{total_memory_limit}Gi",
                "cpu_request": f"{total_cpu_limit // 2}m",
                "memory_request": f"{total_memory_limit * 0.5}Gi"
            },
            "per_pod_resources": pod_resources
        }

    def validate_resources(self, compute_unit: int, replicas: int) -> tuple[bool, list[str]]:
        """
        验证资源分配是否合理
        
        Args:
            compute_unit: 计算单元数量
            replicas: 副本数量
            
        Returns:
            (是否有效, 警告列表)
        """
        warnings = []
        
        if compute_unit <= 0:
            warnings.append("computeUnit必须大于0")
            return False, warnings
        
        if replicas <= 0:
            warnings.append("副本数必须大于0")
            return False, warnings
        
        # 计算每个Pod的资源
        cpu_per_pod = (compute_unit * 1000) / replicas
        memory_per_pod = (compute_unit * 1) / replicas
        
        # 检查资源是否过少
        if cpu_per_pod < 10:
            warnings.append(f"每个Pod的CPU资源({cpu_per_pod:.1f}m)过少，建议减少副本数或增加computeUnit")
        
        if memory_per_pod < 32:
            warnings.append(f"每个Pod的内存资源({memory_per_pod:.1f}Mi)过少，建议减少副本数或增加computeUnit")
        
        # 检查副本数是否过多
        if replicas > compute_unit * 10:
            warnings.append(f"副本数({replicas})相对于computeUnit({compute_unit})过多，可能导致资源不足")
        
        return len(warnings) == 0, warnings
